<!-- 求购苗木 -->
<template>
  <div class="page-container">
    <div class="nav-bar">
      <van-nav-bar
        title="求购苗木"
        left-arrow
        @click-left="onClickLeft"
        fixed
        placeholder
        safe-area-inset-top
      ></van-nav-bar>
    </div>
    <div class="buy-form">
      <van-form @submit="onSubmit">
        <div class="buy-form-item" v-for="(seedingItem, index) in seedingsList" :key="index">
          <div class="item-sort">
            <span>求购苗木{{ index + 1 }}</span>
            <van-image width="20" height="20" :src="getStatus(index)" />
          </div>
          <div>
            <!-- 收货地址 -->
            <van-field
              v-model="seedingItem.receiveCity"
              name="receiveCity"
              label="收货地址"
              placeholder="请选择地区"
              readonly
              required
              is-link
              @click="handleCity(1, index)"
            />

            <!-- 苗木 -->
            <van-field
              v-model="seedingItem.baseProduct"
              name="baseProduct"
              label="选择苗木"
              placeholder="请选择苗木"
              readonly
              required
              is-link
              @click="handleMm(index)"
            />

            <!-- 规格 -->
            <van-field
              name="specification"
              label="选择规格"
              placeholder="至少选择一种规格"
              readonly
              required
              is-link
              @click="handleSpe(index)"
            />

            <!-- 规格信息 -->
            <div class="specification-wrapper" v-if="seedingItem.showSpe">
              <template v-for="(item, idx) in seedingItem.attributes">
                <div v-if="item.selected" class="spe-item">
                  <div class="label">{{ item.attributeName }}</div>
                  <div class="value">
                    <van-field input-align="center" v-model="item.minValue" type="number" />
                    <span>-</span>
                    <van-field input-align="center" v-model="item.maxValue" type="number" />
                  </div>
                  <van-icon name="cross" @click="handleDeleteAttributes(index, idx)" />
                </div>
              </template>

              <div class="spe-item" v-if="seedingItem.quality">
                <div class="label">品质要求</div>
                <div class="value">
                  <van-field
                    disabled
                    class="tag"
                    input-align="center"
                    v-model="seedingItem.qualityName"
                  />
                </div>
                <van-icon name="cross" @click="handleDelete(index, 1)" />
              </div>

              <div class="spe-item" v-if="seedingItem.plantAttributeId">
                <div class="label">种植类型</div>
                <div class="value">
                  <van-field
                    disabled
                    class="tag"
                    input-align="center"
                    v-model="seedingItem.plantAttribute"
                  />
                </div>
                <van-icon name="cross" @click="handleDelete(index, 2)" />
              </div>
            </div>

            <van-field
              v-model="seedingItem.pullNum"
              name="pullNum"
              label="求购数量"
              type="digit"
              placeholder="请输入求购数量"
              required
            />

            <!-- <van-field
              v-model="seedingItem.pullTime"
              name="pullTime"
              label="求购期限"
              placeholder="请选择求购期限"
              required
              readonly
              is-link
              @click="showCommonPicker('求购期限', index)"
            >
              <template #right-icon>
                <span class="deadline-unit">天</span>
              </template>
            </van-field> -->

            <van-field
              v-model="seedingItem.pullTime"
              name="pullTime"
              label="求购期限"
              placeholder="请选择求购期限"
              required
            >
              <template #right-icon>
                <span class="deadline-unit">天</span>
              </template>
            </van-field>

            <van-field class="upload-section margin-t10" name="uploader" label-align="top">
              <template #label>
                <div class="upload-title">
                  上传图片<span class="upload-hint">(最多上传5张)</span>
                </div>
              </template>
              <template #input>
                <van-uploader
                  @delete="(file, detail) => deleteOssIds(file, detail, index)"
                  v-model="seedingItem.images"
                  :max-count="5"
                  :after-read="(file) => afterRead(file, index)"
                  :multiple="true"
                />
              </template>
            </van-field>

            <van-field
              v-model="seedingItem.deliverCity"
              class="margin-t10"
              name="deliverCityCode"
              label="期望货源"
              placeholder="请选择期望货源"
              readonly
              is-link
              @click="handleCity(2, index)"
            />

            <van-field
              class="margin-t10"
              v-model="seedingItem.remark"
              name="remark"
              label="求购描述"
              type="textarea"
              placeholder="请输入求购苗木描述"
              :autosize="{ minHeight: 100 }"
            />

            <!-- 城市选择弹出层 -->
            <van-popup
              v-model:show="seedingItem.showCityPicker"
              position="right"
              :style="{ width: '100%', height: '100%' }"
            >
              <city-index-bar
                :cityType="cityType"
                :seedingIndex="seedingIndex"
                @select="onCitySelect"
                @closeDialog="closeDialog"
              />
            </van-popup>

            <!-- 选择苗木弹窗 -->
            <van-popup
              v-model:show="seedingItem.showMmPicker"
              position="right"
              :style="{ width: '100%', height: '100%' }"
            >
              <mmPicker
                v-model:show="seedingItem.showMmPicker"
                :seedingIndex="seedingIndex"
                @select="onMmSelect"
              >
              </mmPicker>
            </van-popup>

            <!-- 规格选择弹出层 -->
            <van-popup
              v-model:show="seedingItem.showSpecPicker"
              position="right"
              :style="{ width: '100%', height: '100%' }"
            >
              <standard
                ref="standardRef"
                v-model:show="seedingItem.showSpecPicker"
                :baseProductId="seedingsList[seedingIndex].baseProductId"
                :seedingIndex="seedingIndex"
                :quality="seedingsList[seedingIndex].quality"
                :plantAttributeId="seedingsList[seedingIndex].plantAttributeId"
                :attributes="seedingItem.attributes"
                @confirm="onSpecConfirm"
              />
            </van-popup>
          </div>

          <!-- 求购期限选择器 -->
          <common-picker
            :seedingIndex="seedingIndex"
            v-model:show="showPicker"
            :title="title"
            :columns="deadlineColumns"
            :model-value="pickerValue"
            @confirm="onConfirm"
          />
        </div>
      </van-form>
    </div>
    <!-- 底部按钮 -->
    <div class="form-buttons van-hairline--top">
      <van-button class="add-btn" plain type="primary" @click="addMoreSeedlings"
        >添加求购苗木</van-button
      >
      <van-button class="submit-btn" type="primary" block @click="onSubmit">提交</van-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import bridge from '@/utils/bridge.js'
import { ref, reactive } from 'vue'
import CityIndexBar from './components/cityIndexBar.vue'
import mmPicker from './components/mmPicker.vue'
import CommonPicker from './components/CommonPicker.vue'
import Standard from './components/standard.vue'
import { upload, batchAdd } from '@/api'
// 求购期限选项
const deadlineColumns = [
  { text: '1', value: 1 },
  { text: '7', value: 7 },
  { text: '30', value: 30 }
]

interface FormData {
  receiveCity: string
  receiveCityCode: string
  baseProduct: string
  baseProductId: string
  attributes: []
  pullNum: string
  pullTime: string
  deliverCityCode: string
  deliverCity: string
  remark: string
  quality: string
  qualityName: string
  plantAttributeId: string
  plantAttribute: string
  ossId: string
  isOpen: string
  userId: string
  images: []
  showMmPicker: boolean
  showCityPicker: boolean
  showSpecPicker: boolean
}

const formData = reactive<FormData>({
  receiveCity: '',
  receiveCityCode: '',
  baseProduct: '',
  baseProductId: '',
  attributes: [],
  pullNum: '',
  pullTime: '',
  deliverCityCode: '',
  deliverCity: '',
  remark: '',
  quality: '',
  qualityName: '',
  plantAttributeId: '',
  plantAttribute: '',
  ossId: '',
  isOpen: '1',
  userId: '',
  images: [],
  showMmPicker: false,
  showCityPicker: false,
  showSpecPicker: false
})

const seedingsList = reactive([
  {
    receiveCity: '',
    receiveCityCode: '',
    baseProduct: '',
    baseProductId: '',
    attributes: [],
    pullNum: '',
    pullTime: '',
    deliverCityCode: '',
    deliverCity: '',
    remark: '',
    quality: '',
    qualityName: '',
    plantAttributeId: '',
    plantAttribute: '',
    ossId: '',
    isOpen: '1',
    userId: '',
    showSpe: false,
    showMmPicker: false,
    showCityPicker: false,
    showSpecPicker: false
  }
])
const title = ref('')
// 收货地址弹窗
// 区分收货地址与期望货源
const cityType = ref(0)
// 求购苗木编号
const seedingIndex = ref(0)
const standardRef = ref()
// 求购期限弹窗
const showPicker = ref(false)
const pickerValue = ref<number[]>([])

// 选择城市弹窗
const handleCity = (type: number, index: number) => {
  cityType.value = type
  seedingIndex.value = index
  seedingsList[index].showCityPicker = true
}
// 城市选择回调
const onCitySelect = (city: { name: string; code: string }, type: number, index: number) => {
  if (type === 1) {
    seedingsList[index].receiveCity = `${city.parentName}${city.name}`
    seedingsList[index].receiveCityCode = city.code
  } else if (type === 2) {
    seedingsList[index].deliverCity = `${city.parentName}${city.name}`
    seedingsList[index].deliverCityCode = city.code
  }

  seedingsList[index].showCityPicker = false
}

const closeDialog = (index: number) => {
  seedingsList[index].showCityPicker = false
}

// 选择苗木
const handleMm = (index: number) => {
  seedingIndex.value = index
  seedingsList[index].showMmPicker = true
}

// 选择苗木回调
const onMmSelect = (data: any, index: number) => {
  seedingsList[index].showMmPicker = false
  seedingsList[index].showSpe = false
  seedingsList[index].baseProduct = data.productName
  seedingsList[index].baseProductId = data.baseProductId
  seedingsList[index].attributes = []
  seedingsList[index].quality = ''
  seedingsList[index].qualityName = ''
  seedingsList[index].plantAttributeId = ''
  seedingsList[index].plantAttribute = ''
}

// 选择规格
const handleSpe = (index: number) => {
  seedingIndex.value = index
  if (seedingsList[index].baseProductId) {
    seedingsList[index].showSpecPicker = true
  } else {
    showToast('请选择苗木')
  }
}

// 规格选择回调
const onSpecConfirm = (specs: any, quality: any, category: any, index: any) => {
  seedingsList[index].showSpe = true
  seedingsList[index].attributes = specs
  seedingsList[index].quality = quality ? quality.dictLabel : ''
  seedingsList[index].qualityName = quality ? quality.dictValue : ''
  seedingsList[index].plantAttributeId = category ? category.plantAttributeId : ''
  seedingsList[index].plantAttribute = category ? category.plantAttributeName : ''
}

// 删除规格
const handleDeleteAttributes = (idx1: any, idx2: any) => {
  seedingsList[idx1].attributes[idx2].selected = false
  seedingsList[idx1].attributes[idx2].minValue = null
  seedingsList[idx1].attributes[idx2].maxValue = null
}

// 删除品质要求 || 删除终止类型 TODO
const handleDelete = (idx: any, type: any) => {
  if (type === 1) {
    seedingsList[idx].quality = ''
  } else {
    seedingsList[idx].plantAttributeId = ''
  }
  if (standardRef.value) {
    standardRef.value.updateInfo()
  }
}

const showCommonPicker = (str: string, index: number) => {
  seedingIndex.value = index
  showPicker.value = true
  title.value = str
}

// 求购期限选择
const onConfirm = (selectedValues: any, index: number) => {
  seedingsList[index].pullTime = selectedValues.selectedOptions[0].text
}

// 提交表单
const onSubmit = async () => {
  let valid = true

  seedingsList.map((seeding, index) => {
    if (!seeding.receiveCityCode) {
      valid = false
      return showToast('请选择收货地址')
    }
    if (!seeding.baseProductId) {
      valid = false
      return showToast('请选择苗木')
    }
    if (!seeding.pullNum) {
      valid = false
      return showToast('请输入求购数量')
    }
    if (!seeding.pullTime) {
      valid = false
      return showToast('请选择求购期限')
    }
    // if (!seeding.ossId) {
    //   valid = false
    //   return showToast('请上传图片')
    // }
    if (seeding.attributes.length === 0) {
      return showToast(`请选择规格`)
    } else {
      seeding.attributes.some((item: any) => {
        if (item.selected) {
          if (!item.minValue || !item.maxValue) {
            valid = false
            return showToast(`请输入${item.attributeName}`)
          }
        }
      })
    }
  })

  if (valid) {
    let res = await batchAdd(seedingsList)
    if (res.code === 200) {
      showToast(res.msg)
      bridge.closeWebView()
    }
  }
}

// 添加更多苗木
const addMoreSeedlings = () => {
  seedingsList.push(formData)
}

// 图片上传后的处理
const afterRead = async (file: any, index: any) => {
  let data = new FormData()
  if (file.file) {
    file.status = 'uploading'
    file.message = '上传中...'
    data.append('files', file.file)
  } else {
    file.map((item: any) => {
      item.status = 'uploading'
      item.message = '上传中...'
      data.append('files', item.file)
    })
  }
  let res = await upload(data)
  if (res.code === 200) {
    if (file.file) {
      file.status = 'done'
      file.message = '上传成功'
    } else {
      file.map((item: any) => {
        item.status = 'done'
        item.message = '上传成功'
      })
    }

    res.data.map((item: any) => {
      if (seedingsList[index].ossId) {
        seedingsList[index].ossId = `${seedingsList[index].ossId},${item.ossId}`
      } else {
        seedingsList[index].ossId = `${item.ossId}`
      }
    })
  }
}

// 删除图片
const deleteOssIds = (file: any, detail: any, index: any) => {
  let arr = seedingsList[index].ossId.split(',')
  arr.splice(detail.index, 1)
  seedingsList[index].ossId = arr.join(',')
}

// 动态计算图片路径
const getStatus = computed(() => {
  const IMAGES = {
    error: new URL('/src/assets/error.png', import.meta.url).href,
    success: new URL('/src/assets/success.png', import.meta.url).href
  }
  return (index) => {
    if (
      !seedingsList[index].receiveCityCode ||
      !seedingsList[index].baseProductId ||
      !seedingsList[index].pullNum ||
      !seedingsList[index].pullTime ||
      !seedingsList[index].ossId ||
      seedingsList[index].attributes.length === 0
    ) {
      return IMAGES.error
    } else if (seedingsList[index].attributes.length > 0) {
      let res = seedingsList[index].attributes.filter((item) => item.selected)
      return res.length > 0 ? IMAGES.error : IMAGES.success
    } else {
      return IMAGES.success
    }
  }
})

const onClickLeft = () => {
  bridge.closeWebView()
}
onMounted(() => {
  bridge.setNavigationBarVisible({
    value: '0'
  })
})
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  background-color: #fff;

  :deep(.nav-bar) {
    .van-nav-bar__arrow {
      color: #222;
      font-size: 17px;
    }

    .van-nav-bar__title {
      font-size: 17px;
      font-weight: normal;
      color: #222;
    }
  }

  .buy-form {
    flex: 1;
    background-color: #f5f5f5;
    overflow-y: auto;

    .buy-form-item {
      margin-bottom: 10px;

      .item-sort {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 12px;
        background: linear-gradient(to right, #c4f4e2 0%, #8de1c9 100%);
        height: 45px;
        color: #222;
        font-weight: 400;
        font-size: 16px;
        line-height: 45px;

        span {
          display: flex;
          align-items: center;

          &::before {
            content: '';
            display: block;
            margin-right: 4px;
            width: 5px;
            height: 15px;
            background: #32bc05;
          }
        }
      }

      :deep(.van-cell) {
        padding-left: 12px;
        padding-right: 12px;
      }

      :deep(.van-field__label) {
        font-size: 15px;
      }

      :deep(.van-field__body) {
        font-size: 14px;
      }

      :deep(.van-uploader__upload) {
        width: 74px;
        height: 74px;
      }

      :deep(.van-image) {
        width: 74px;
        height: 74px;
      }
    }
  }

  .margin-t10 {
    margin-top: 10px;
  }

  .upload-section {
    padding: 16px;

    .upload-title {
      margin-bottom: 8px;
      font-size: 14px;

      .upload-hint {
        color: #999;
        margin-left: 4px;
      }
    }
  }

  .deadline-unit {
    color: #666;
    margin-left: 4px;
  }

  .form-buttons {
    background: #fff;
    padding: 13px 16px;
    display: flex;
    gap: 10px;
    width: 100%;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

    :deep(.van-button) {
      height: 45px;
      flex: 1;
      border-radius: 23px;
      font-size: 16px;
    }

    :deep(.add-btn) {
      border-color: #32bc05;
      color: #32bc05;
    }

    :deep(.submit-btn) {
      color: #fff;
      background: #32bc05;
      border: none;
    }

    :deep(.van-hairline--top:after) {
      border-color: #eee !important;
    }
  }

  .specification-wrapper {
    padding: 10px 14px;

    .spe-item {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-bottom: 4px;

      .label {
        width: 60px;
        color: #999;
        font-size: 14px;
      }

      .value {
        display: flex;
        align-items: center;
        gap: 5px;
        color: #999;
        width: 180px;

        .van-cell {
          padding: 0;
          width: 80px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          background: #f5f5f5;
          border: 1px solid #ddd;
          border-radius: 2px;

          :deep(.van-field__control) {
            color: #999;
          }

          &.tag {
            border-color: #32bc05;
          }

          :deep(.van-field__control:disabled) {
            color: #32bc05 !important;
            -webkit-text-fill-color: #32bc05 !important;
          }
        }
      }

      .van-icon {
        color: #999;
      }
    }
  }
}
</style>
